﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BulldogCMS.Data.Templates
{
    public class Template : ITemplate
    {
        private List<Fields.IFieldDefinition> _fieldDefinitions = new List<Fields.IFieldDefinition>();
        private List<string> _useTemplateNames = new List<string>();
        private List<string> _allowTemplateNames = new List<string>();
        
        public string BaseTemplateName
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public string FullName
        {
            get;
            set;
        }

        public bool AllowAllTemplates
        {
            get;
            set;
        }

        internal void AddAllowTemplateName(string templateName) {
            this._allowTemplateNames.Add(templateName);
        }

        internal void AddUseTemplateName(string templateName)
        {
            this._useTemplateNames.Add(templateName);
        }

        internal void AddFieldDefinition(Fields.IFieldDefinition fieldDefinition)
        {
            this._fieldDefinitions.Add(fieldDefinition);
        }

        public IEnumerable<Fields.IFieldDefinition> FieldDefinitions
        {
            get {
                return this._fieldDefinitions;
            }
        }

        public ITemplatesProvider TemplatesProvider
        {
            get;
            internal set;
        }

        public IEnumerable<ITemplate> UseTemplates
        {
            get
            {
                foreach (string templateName in this._useTemplateNames)
                {
                    ITemplate template = this.TemplatesProvider.GetTemplate(templateName);
                    if (template != null)
                    {
                        yield return template;
                    }
                    else
                    {
                        throw new Exceptions.TemplateNotFoundException("Template with name {0} not found. Referenced by {1}.".Fill(templateName, this.FullName));
                    }
                }
            }
        }

        public IEnumerable<ITemplate> AllowTemplates
        {
            get
            {
                foreach (string templateName in this._allowTemplateNames)
                {
                    ITemplate template = this.TemplatesProvider.GetTemplate(templateName);
                    if (template != null)
                    {
                        yield return template;
                    }
                    else
                    {
                        throw new Exceptions.TemplateNotFoundException("Template with name {0} not found. Referenced by {1}.".Fill(templateName, this.FullName));
                    }
                }
            }
        }

    }
}
